package com.yxq.mdt.app.modules.socialcontact.ui.fragment.main;

import android.content.Intent;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.socialcontact.adapter.MainSocialContactNearAdapter;
import com.yxq.mdt.app.modules.socialcontact.adapter.PossibleListAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.NearManAndDynamicBean;
import com.yxq.mdt.app.modules.socialcontact.bean.NearManAndDynamicTopicBean;
import com.yxq.mdt.app.modules.socialcontact.bean.PerfectBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SelectNearbyListBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialNearContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialNearPresenter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTheHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.NearbyListActivity;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialPersonalHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialStateDetailsAc;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.Jzvd;
import q.rorbin.badgeview.DisplayUtil;

/**
 * 社区附近
 */
public class NearbyFragment extends BaseFragment<MainSocialNearPresenter> implements MainSocialNearContract.View {
    @BindView(R.id.social_state_recyclerView)
    RecyclerView socialStateRecyclerView;
    MainSocialContactNearAdapter mainSocialContactNearAdapter;
    @BindView(R.id.possible_recycler)
    RecyclerView possibleRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.look_all)
    RelativeLayout lookAll;
    private List<NearManAndDynamicBean> nearManAndDynamicBeans;
    PossibleListAdapter possibleListAdapter;
    double mapLng, mapLat;
    private List<NearManAndDynamicTopicBean.ListBean> mainSocialContactRecommendBean;

    @Override
    protected int attachLayoutId() {
        setImmersionBarEnabled(false);
        return R.layout.fragment_nearby_fragment;
    }

    @Override
    protected MainSocialNearPresenter getPresenter() {
        return new MainSocialNearPresenter(this, new MainSocialContactModel());
    }


    @Override
    public void initView(View view) {
        if (Hawk.contains(SPKey.SP_KEY_USER_ADDRESS_MAP_LNG)) {
            mapLng = Hawk.get(SPKey.SP_KEY_USER_ADDRESS_MAP_LNG);
            mapLat = Hawk.get(SPKey.SP_KEY_USER_ADDRESS_MAP_LAT);
        }
        if (mapLng == 0 || mapLat == 0) {
            mapLng = 106.63043;
            mapLat = 29.71798;
        }
        mainSocialContactRecommendBean = new ArrayList<>();
        nearManAndDynamicBeans = new ArrayList<>();

        socialStateRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mainSocialContactNearAdapter = new MainSocialContactNearAdapter(R.layout.item_layout_dynamic_list, mainSocialContactRecommendBean);
        socialStateRecyclerView.setAdapter(mainSocialContactNearAdapter);
        mainSocialContactNearAdapter.setOnItemClickListener((adapter, view1, position) -> {
            if (mainSocialContactNearAdapter.countDownTimer != null) {
                mainSocialContactNearAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mContext, SocialStateDetailsAc.class);
            startActivity(it);
        });
        socialStateRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        socialStateRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mainSocialContactNearAdapter.countDownTimer != null) {
                    mainSocialContactNearAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }

            }
        });
        possibleRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        possibleListAdapter = new PossibleListAdapter(R.layout.item_possible_icon_list, nearManAndDynamicBeans);
        possibleRecycler.setAdapter(possibleListAdapter);
        possibleRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                if (0 != position) {
                    outRect.left = DisplayUtil.dp2px(mContext, -10);
                }
            }

        });
        lookAll.setOnClickListener(view12 -> {
            if (mainSocialContactNearAdapter.countDownTimer != null) {
                mainSocialContactNearAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent intent = new Intent(mContext, NearbyListActivity.class);
            startActivity(intent);
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getNearManAndDynamic(String.valueOf(mapLng), String.valueOf(mapLat));
            mPresenter.getNearManAndDynamicTopic(String.valueOf(mapLng), String.valueOf(mapLat), page, 20);
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getNearManAndDynamic(String.valueOf(mapLng), String.valueOf(mapLat));
            mPresenter.getNearManAndDynamicTopic(String.valueOf(mapLng), String.valueOf(mapLat), page, 20);
        });
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableAutoLoadMore(true);
    }

    @Override
    public void initData() {
        mPresenter.getNearManAndDynamic(String.valueOf(mapLng), String.valueOf(mapLat));
        mPresenter.getNearManAndDynamicTopic(String.valueOf(mapLng), String.valueOf(mapLat), page, 20);

    }

    public void refresh() {
        page = 1;
        mPresenter.getNearManAndDynamic(String.valueOf(mapLng), String.valueOf(mapLat));
        mPresenter.getNearManAndDynamicTopic(String.valueOf(mapLng), String.valueOf(mapLat), page, 20);
    }

    @Override
    public void setData(@Nullable Object data) {

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mainSocialContactNearAdapter.countDownTimer != null) {
            mainSocialContactNearAdapter.countDownTimer.onFinish();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mainSocialContactNearAdapter.countDownTimer != null) {
            mainSocialContactNearAdapter.countDownTimer.cancel();
        }
        Jzvd.goOnPlayOnPause();
        MediaPlayerHelper.realese();
    }

    @Override
    public void onLoadNearManAndDynamicSuccess(String s) {
        if (s != null) {
            List<NearManAndDynamicBean> list = JSON.parseArray(s, NearManAndDynamicBean.class);
            nearManAndDynamicBeans.addAll(list);
            possibleListAdapter.setNewData(nearManAndDynamicBeans);
        }
        possibleListAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mainSocialContactNearAdapter.countDownTimer != null) {
                mainSocialContactNearAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent intent = new Intent(mContext, NearbyListActivity.class);
            startActivity(intent);
        });

    }

    @Override
    public void onLoadNearManAndDynamicFailed() {

    }

    @Override
    public void onLoadSelectMyNearbySuccess(SelectNearbyListBean selectNearbyListBean) {

    }

    @Override
    public void onLoadSelectMyNearbyFailed() {

    }

    @Override
    public void onLoadNearManAndDynamicTopicSuccess(NearManAndDynamicTopicBean nearManAndDynamicTopicBean) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (page == 1) {
            mainSocialContactNearAdapter.setNewData(nearManAndDynamicTopicBean.getList());
        } else {
            if (nearManAndDynamicTopicBean.getList() != null && nearManAndDynamicTopicBean.getList().size() != 0) {
                mainSocialContactNearAdapter.addData(nearManAndDynamicTopicBean.getList());
                mainSocialContactNearAdapter.notifyDataSetChanged();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
        mainSocialContactNearAdapter.notifyDataSetChanged();
        mainSocialContactNearAdapter.setOnItemClickListener((adapter, view1, position) -> {
            if (mainSocialContactNearAdapter.countDownTimer != null) {
                mainSocialContactNearAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mContext, SocialStateDetailsAc.class);
            it.putExtra("topicId", mainSocialContactNearAdapter.getItem(position).getId());
            it.putExtra("id", mainSocialContactNearAdapter.getItem(position).getId());
            startActivity(it);
        });
        mainSocialContactNearAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.item_layout_nike_img:
                    if (mainSocialContactNearAdapter.countDownTimer != null) {
                        mainSocialContactNearAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent it = new Intent(mContext, SocialPersonalHomepageAc.class);
                    it.putExtra("userId", mainSocialContactNearAdapter.getItem(position).getCreateMan());
                    startActivity(it);
                    break;
                case R.id.item_layout_content_browse:
                case R.id.item_layout_content_browse_img:
                case R.id.item_layout_content_browse_lint:
                    int giveNum = mainSocialContactNearAdapter.getItem(position).getUpCount();
                    if (mainSocialContactNearAdapter.getData().get(position).getGiveLike() != 0) {
                        MainSocialContactModel.delGsTopicFavour("2", mainSocialContactNearAdapter.getItem(position).getId(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                mainSocialContactNearAdapter.getItem(position).setGiveLike(0);
                                mainSocialContactNearAdapter.getItem(position).setUpCount(giveNum - 1);
                                mainSocialContactNearAdapter.notifyDataSetChanged();
                                showCenterToast("取消点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("取消点赞失败");
                            }
                        });
                    } else {
                        MainSocialContactModel.saveGsTopicFavour(mainSocialContactNearAdapter.getItem(position).getId(), "2", new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                showCenterToast("点赞成功");
                                mainSocialContactNearAdapter.getItem(position).setGiveLike(1);
                                mainSocialContactNearAdapter.getItem(position).setUpCount(giveNum + 1);
                                mainSocialContactNearAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("点赞失败");
                            }
                        });
                    }

                    break;
                case R.id.item_layout_attention:
                    TextView attention = view.findViewById(R.id.item_layout_attention);
                    MainSocialContactModel.setInterestRelation(mainSocialContactNearAdapter.getItem(position).getCreateMan() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            for (NearManAndDynamicTopicBean.ListBean listBean : mainSocialContactNearAdapter.getData()) {
                                if (listBean.getCreateMan() == mainSocialContactNearAdapter.getItem(position).getCreateMan()) {
                                    listBean.setConcern(1);
                                    mainSocialContactNearAdapter.notifyDataSetChanged();
                                }
                            }
                            attention.setVisibility(View.GONE);
                            showCenterToast("关注成功");
                        }

                        @Override
                        public void onError(String errMsg) {
                            showCenterToast("关注失败");
                        }
                    });
                    break;
                case R.id.group_lint:
                    if (mainSocialContactNearAdapter.countDownTimer != null) {
                        mainSocialContactNearAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent intent = new Intent(mContext, CircleTheHomepageAc.class);
                    intent.putExtra("id", mainSocialContactNearAdapter.getItem(position).getGroupId());
                    intent.putExtra("CircleName", mainSocialContactNearAdapter.getItem(position).getGroupName());
                    startActivity(intent);
                    break;
                case R.id.item_tv_subject:
                    if (mainSocialContactNearAdapter.countDownTimer != null) {
                        mainSocialContactNearAdapter.countDownTimer.cancel();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent goIt = new Intent(mContext, SocialStateDetailsAc.class);
                    goIt.putExtra("topicId", mainSocialContactNearAdapter.getItem(position).getId());
                    goIt.putExtra("id", mainSocialContactNearAdapter.getItem(position).getId());
                    startActivity(goIt);
                    break;
                case R.id.item_layout_content_share:
                    //分享
                    ShareBean shareBean = new ShareBean();
                    if (!TextUtils.isEmpty(mainSocialContactNearAdapter.getItem(position).getContent())) {
                        shareBean.setTitle(mainSocialContactNearAdapter.getItem(position).getContent());//文本
                        shareBean.setText(mainSocialContactNearAdapter.getItem(position).getContent());//文本
                    } else {
                        shareBean.setTitle("社交电商新玩法，好玩让你意想不到。");//文本
                        shareBean.setText("社交电商新玩法，好玩让你意想不到。");//文本
                    }
                    shareBean.setShareType("0");//图文分享
                    shareBean.setShareTypeAPP(2);
                    shareBean.setHandleId(mainSocialContactNearAdapter.getItem(position).getId());
                    if (mainSocialContactNearAdapter.getItem(position).getTopicFileList() != null && mainSocialContactNearAdapter.getItem(position).getTopicFileList().size() > 0 && "1".equals(mainSocialContactNearAdapter.getItem(position).getTopicFileList().get(0).getClass1())) {
                        shareBean.setImageUrl(mainSocialContactNearAdapter.getItem(position).getTopicFileList().get(0).getFile());//LOGO
                    } else {
                        shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                    }
                    if (!"release".equals(BuildConfig.RELEASE)) {
                        shareBean.setUrl("http://testpm.quai69.com/webtrends.html?topicId="+mainSocialContactNearAdapter.getItem(position).getId()+"&platform=2&parent_id=" + getParentId());//分享URL
                    } else {
                        shareBean.setUrl("http://pm.quai69.com/webtrends.html?topicId="+mainSocialContactNearAdapter.getItem(position).getId()+"&platform=2&parent_id=" + getParentId());
                    }
                    ShareSheetDialog shareSheetDialog = new ShareSheetDialog(shareBean, false);
                    shareSheetDialog.show(getChildFragmentManager(), "shareSheetDialog");
                    break;
            }
        });
    }


    @Override
    public void onLoadNearManAndDynamicTopicFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadQueryIsPerfectFailed() {

    }

    @Override
    public void onLoadQueryIsPerfectSuccess(PerfectBean s) {

    }

}
